<?php

/**
 * 文件名：AlidayuSms.php
 * 创建日期：2018/8/28
 * 创建时间：16:31
 * 创建者：kun
 **/

namespace kkk\sms;

use Aliyun\DySDKLite\SignatureHelper;
use think\Exception;
use think\Validate;

class AlidayuSms
{
    /**
     * 阿里大鱼key
     * @var
     */
    protected $accessKeyId;

    /**
     * 阿里大鱼秘钥
     * @var
     */
    protected $accessKeySecret;

    /**
     * 阿里大鱼签名
     * @var
     */
    protected $signName;

    protected $error;

    /**
     * 构造方法
     * AlidayuSms constructor.
     * @param array $options
     * $option = [
     *      "access_key_id"     => '阿里大鱼key',
     *      "access_secret"     => '阿里大鱼秘钥',
     *      "sign_name"         => '阿里大鱼签名',
     * ]
     */
    public function __construct($options=[]){
        ini_set('date.timezone','Asia/Shanghai');
        date_default_timezone_set("GMT");
        // 获取config中的阿里大鱼短信配置
        $config = config('alidy');
        // 根据场景赋值
        isset($options["access_key_id"]) ? $this->accessKeyId   = $options["access_key_id"] : $config['access_key_id'];
        isset($options["access_secret"]) ? $this->accessSecret  = $options["access_secret"] : $config['access_key_id'];
        isset($options["sign_name"])     ? $this->signName      = $options["sign_name"]     : $config['sign_name'];
    }

    /**
     * 发送短息验证码
     * @param string $phone
     * @param string $code
     * @param string $template_code
     * @return bool|\stdClass
     * @throws Exception
     */
    public function send_sms_code($phone = "", $code = "", $template_code = "")
    {

        if (!$this->checkParams($phone, $code, $template_code )) {
            throw  new  Exception($this->error);
        }

        // fixme 必填: 短信接收号码
        $params["PhoneNumbers"] = $phone;

        // fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
        $params["TemplateCode"] = $template_code;

        // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
        $params['template_param'] = [
            "code" => $code,
        ];
        if(!empty($params["template_param"]) && is_array($params["template_param"])) {
            $params["template_param"] = json_encode($params["template_param"], JSON_UNESCAPED_UNICODE);
        }

        // 初始化SignatureHelper实例用于设置参数，签名以及发送请求
        $helper = new SignatureHelper();

        // 此处可能会抛出异常，注意catch
        $content = $helper->request(
            $this->accessKeyId,
            $this->accessKeySecret,
            "dysmsapi.aliyuncs.com",
            array_merge($params, array(
                "RegionId" => "cn-hangzhou",
                "Action" => "SendSms",
                "Version" => "2017-05-25",
            ))
        // fixme 选填: 启用https
        // ,true
        );

        return $content;
    }

    /**
     * 检测对应的参数是否存在
     * @param string $phone             手机号码
     * @param string $code              验证码
     * @param string $template_code     短信模板code
     * @return bool
     */
    protected function checkParams($phone="",$code="",$template_code=""){
        if (empty($this->accessKeyId) || empty($this->accessKeySecret) || empty($template_code)  ){
            $this->error = "获取短息发送接口参数缺失";
            return false;
        }
        $validate = new Validate([
            ['phone','require|regex:/1[34578]{1}\d{9}$/','手机号不能为空|手机号错误'],
            ['code','require','验证码不存在'],
        ]);
        $data=[
            "phone"=>$phone,
            "code"=>$code,
        ];
        if (!$validate->check($data)) {
            $this->error = $validate->getError();
            return false;
        }
        return true;
    }


}